package de.herberlin.server.mail;

import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

import de.herberlin.wwwutil.httperror.HttpError;

public class MailHeader  {

	private Map headers=new Properties();
	private StringBuffer content=new StringBuffer();
	private boolean  readHeader=true;

	public MailHeader() throws HttpError {
	}

	public String getContent() {
		return content.toString();
	}
	public String[][] getHeader() {
		String[][] result=new String[headers.size()][2];
		Iterator it=headers.keySet().iterator();
		int counter=0;
		while (it.hasNext() ) {
			String key=(String)it.next();
			String value=(String)headers.get(key);
			result[counter][0]=key;
			result[counter][1]=value;
			counter++;
		}
		return result;
	}

	public void addLine(String aLine) {
		if (aLine==null) return;
		if ("".equals(aLine)) {
			// end of headers
			readHeader=false;
			return;
		}
		if (readHeader) {
			String[] parsed=aLine.split(":",2);
			if (parsed.length==1 && parsed[0]!=null && parsed[0].indexOf("boundary")>-1)  {
				headers.put("CONTENT-TYPE",headers.get("CONTENT-TYPE")+parsed[0]);
			}
			if (parsed.length<2 || parsed[0]==null || parsed[1]==null) return;
			headers.put(parsed[0].trim().toUpperCase(),parsed[1].trim());
		} else {
			content.append(aLine);
			content.append("\n");
		}
	}

	public String toString() {
		return (String) headers.get("FROM");
	}
}
